<template>
  <div class="container" v-loading="loading">
    <!-- 工具栏 -->
    <div class="table-toolbar">
      <el-button link @click="handleAdd" style="color: #1aa1fb">
        <el-icon style="margin-right: 3px"><Plus /></el-icon>
        添加
      </el-button>
    </div>
    <!-- 表格 -->
    <CLTable
      :fields="referenceFields"
      :initial-data="tableData"
      line-height="low"
      :table-config="tableConfig"
      :more-actions="moreActions"
      @node-selected="handleNodeSelected"
      @on-more-action="handleMoreAction"
      @pagerChange="pagerChange"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from "vue";
  import CLTable from "@/components/CLTable/index.vue";
  import { Plus } from "@element-plus/icons-vue";
  import { ElMessage, ElMessageBox } from "element-plus";
  import {
    getTaskRelationList,
    deleteRelationTask,
    createRelationTask,
    editRelationTask,
    getTaskList,
  } from "./api.ts";
  const props = defineProps(["detail", "subTask"]);
  const loading = ref(false);
  const tableData = ref<any[]>([]);
  const selectedFiles = ref<any[]>([]);

  /**
   * @description 处理新增
   */
  const handleAdd = () => {
    tableData.value.push({});
  };

  /**
   * @description 监听分页变化
   */
  const pagerChange = (args: any) => {
    loadData(args.currentPage, args.pageSize);
  };

  const referenceFields = ref<any[]>([
    {
      id: 1,
      name: "关联类型",
      field: "preOrFollowType",
      typex: "single",
      invisible: true,
      checked: true,
      disable: false,
      options: [],
    },
    {
      id: 2,
      name: "关联任务",
      field: "id",
      typex: "single",
      invisible: true,
      checked: true,
      disable: false,
      options: [],
    },
    {
      id: 3,
      name: "相关性",
      field: "relationType",
      typex: "single",
      invisible: true,
      checked: true,
      disable: false,
      options: [],
    },
  ]);

  const tableConfig = ref({
    tableH: "calc(100vh - 230px)",
    page: {
      showOperationsColumn: true,
      enable: true,
      pageSizes: [10, 20, 50, 100],
      size: "small",
      disabled: false,
      background: true,
      layout: "total, sizes, prev, pager, next, jumper",
    },
    OperationsColumnMode: "textIcon", // 操作列模式，text为文本模式
    OperationsColumnWidth: 100, //自定义操作列宽度
    borderMode: "none", // 表格边框模式，none为无边框
    editable: true,
  });

  // 更多操作配置
  const moreActions = ref([
    { key: "save", label: "保存" },
    { key: "delete", label: "删除" },
  ]);

  const handleMoreAction = (actionKey: string, node: any) => {
    const KEYMAP: any = {
      save: handleSave,
      delete: handleDelete,
    };
    KEYMAP[actionKey]?.(node);
  };

  /**
   * @description 获取全部任务
   */
  const getTaskitems = async () => {
    loading.value = true;
    try {
      const params = {
        conditions: [
          {
            field: "projectId",
            operator: "=",
            value: props?.detail?.projectId,
          },
        ],
        pageNo: 1,
        pageSize: 99999,
      };
      const { result } = await getTaskList(params);
      const optionList =
        (result as any)?.map((ele: any) => ({
          label: ele?.name?.["zh_CN"],
          value: ele?.id,
        })) ?? [];
      referenceFields.value = [
        {
          id: 1,
          name: "关联类型",
          field: "preOrFollowType",
          typex: "single",
          invisible: true,
          checked: true,
          disable: false,
          options: [
            { label: "前置任务", value: "PRE" },
            { label: "后置任务", value: "FOLLOW" },
          ],
        },
        {
          id: 2,
          name: "关联任务",
          field: "id",
          typex: "single",
          invisible: true,
          checked: true,
          disable: false,
          options: optionList,
        },
        {
          id: 3,
          name: "相关性",
          field: "relationType",
          typex: "single",
          invisible: true,
          checked: true,
          disable: false,
          options: [
            { label: "完成-开始(FS)", value: "FS" },
            { label: "开始-完成(SF)", value: "SF" },
            { label: "开始-开始(SS)", value: "SS" },
            { label: "完成-完成(FF)", value: "FF" },
          ],
        },
      ];
      loadData(1, 99999);
    } catch (error) {
      ElMessage.error("加载数据失败");
    }
  };

  // 方法
  const loadData = async (numberPage: number, sizePage: number) => {
    loading.value = true;
    try {
      const params = {
        relationSearchRequest: {
          conditions: [
            {
              field: "preTaskId",
              value: props.detail?.id,
            },
            {
              field: "followTaskId",
              value: props.detail?.id,
            },
          ],
          logic: "or",
          pageNo: numberPage ?? 1,
          pageSize: sizePage ?? 99999,
        },
        taskSearchRequest: {
          conditions: [],
          pageNo: numberPage ?? 1,
          pageSize: sizePage ?? 99999,
        },
      };

      // 如果需要调用真实 API，取消下面的注释
      const { result } = await getTaskRelationList(props?.detail?.id, params);
      tableData.value =
        (result as any)?.map((ele: any) => ({
          ...ele,
          relationType: ele?.relationType?.value,
          preOrFollowType: ele.preOrFollowType,
        })) ?? [];
      props.subTask("relate", result?.length ?? 0);
    } catch (error) {
      ElMessage.error("加载数据失败");
    } finally {
      loading.value = false;
    }
  };

  const handleNodeSelected = (nodes: any[]) => {
    selectedFiles.value = nodes;
  };

  /**
   * @description 处理保存
   */
  const handleSave = async (node: any) => {
    loading.value = true;
    try {
      const params = {
        preTaskId: Object.is("PRE", node.preOrFollowType)
          ? node.id
          : props.detail?.id,
        followTaskId: Object.is("FOLLOW", node.preOrFollowType)
          ? node.id
          : props.detail?.id,
        projectId: props?.detail?.projectId,
        id: node.id,
        preOrFollowType: node.preOrFollowType,
        type: node.relationType,
      };
      if (Object.keys(node)?.length > 3) {
        await editRelationTask({ ...params });
        ElMessage.success("保存成功");
        loadData(1, 99999);
        return false;
      }
      await createRelationTask(params);
      ElMessage.success("保存成功");
      loadData(1, 99999);
    } catch (error) {
      ElMessage.error("保存失败");
    }
  };

  const handleDelete = async (node: any) => {
    try {
      await ElMessageBox.confirm(`确定要删除吗？`, "确认删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });
      loading.value = true;
      await deleteRelationTask(props.detail.id, node.id);
      ElMessage.success("删除成功");
      loadData(1, 99999);
    } catch (error) {
      ElMessage.error("删除失败");
    }
  };

  // 生命周期
  onMounted(() => {
    getTaskitems();
  });

  // 暴露方法给父组件
  defineExpose({
    loadData,
    refresh: loadData,
  });
</script>

<style scoped lang="scss">
  .container {
    box-sizing: border-box;
    padding-right: 10px;
    margin-top: 2px;
    .table-toolbar {
      display: flex;
      flex-direction: row;
      align-items: center;
      padding: 10px 0px;
      color: #5e5e5e;
      font-size: 14px;

      :deep(.el-button.is-link) {
        font-weight: 400;
      }
    }
  }

  .relation {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
  }
</style>
